package com.apes.framework.jpa;

import lombok.SneakyThrows;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 功能：连接器，获取数据库存连接
 *
 * @author xul
 * @create 2018-03-01 16:54
 */
@Service
public class Connector {

    @Autowired
    EntityManager em;

    public EntityManager getEm() {
        return em;
    }

    @SneakyThrows
    public Connection getConnection() {
        Session session = em.unwrap(Session.class);
        MyWork myWork = new MyWork();
        session.doWork(myWork);
        Connection connection = myWork.getConnection();
        if (connection.isClosed()) {
            connection = getConnection();
        }
        return connection;
    }

    private static class MyWork implements Work {

        Connection connection;

        @Override
        public void execute(Connection connection) {
            this.connection = connection;
        }

        Connection getConnection() {
            return connection;
        }
    }


    public void test() {
        Connection conn;
        try {
            conn = getConnection();
            Statement st = conn.createStatement();
            String sql = " SELECT 1 FROM DUAL ";
            st.execute(sql);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}